package com.atguigu.gulimall.auth.web.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeException;
import com.atguigu.common.to.MemberTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.vo.UserVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户登录
 *
 * @author DuGuanghan
 * @since 2024-08-16 16:21:38
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 获取短信验证码
     *
     * @param phone 手机号
     * @return {@link R }
     * @author DuGuanghan
     * @since 2024-08-23 10:33:33
     */
    @GetMapping("/sms/code")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO 接口防刷

        // 从Redis中获取手机号对应的验证码
        String sendCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_SEND_CODE_PREFIX + phone);
        if (!StringUtils.isEmpty(sendCode)) {
            long time = Long.parseLong(sendCode.split("_")[1]);
            if ((System.currentTimeMillis() - time) < 60*1000) {
                return R.error(BizCodeException.SMS_SEND_TIMEOUT.getCode(), BizCodeException.SMS_SEND_TIMEOUT.getMsg());
            }
        }

        // 生成验证码
        String code = generateVerificationCode();

        // 将验证码和手机号存入Redis
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_SEND_CODE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);

        // 发送验证码
        thirdPartyFeignService.sendCode(phone, code);

        return R.ok();
    }

    /**
     * 注册用户
     *
     * @param userVO   用户
     * @param bind     异常结果
     * @param redirect 重定向属性
     * @return {@link String }
     * @author DuGuanghan
     * @since 2024-08-21 15:55:40
     */
    @PostMapping("/regist")
    public String regist(@Valid UserVO userVO, BindingResult bind, RedirectAttributes redirect) {
        if (bind.hasErrors()) {
            Map<String, String> map = bind.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirect.addFlashAttribute("error", map);

            return "redirect:http://auth.gulimall.com/regist.html";
        }

        // 校验验证码正确性
        String sendCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_SEND_CODE_PREFIX + userVO.getPhone());
        if (!StringUtils.isEmpty(sendCode)) {
            // 判断用户提交的验证码与发送的验证码是否一致
            String code = sendCode.split("_")[0];
            if (code.equals(userVO.getCode())) {
                // 验证通过后删除redis中的验证码
                redisTemplate.delete(AuthServerConstant.SMS_SEND_CODE_PREFIX + userVO.getPhone());
                // 注册会员
                R r = memberFeignService.regist(userVO);
                if (r.getCode() == 0) {
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("msg", (String) r.get("msg"));
                    redirect.addFlashAttribute("error", map);

                    return "redirect:http://auth.gulimall.com/regist.html";
                }
            } else {
                HashMap<String, String> map = new HashMap<>();
                map.put("code", "验证码输入有误，请重新输入");
                redirect.addFlashAttribute("error", map);

                return "redirect:http://auth.gulimall.com/regist.html";
            }
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("code", "验证码已过期，请重新获取");
            redirect.addFlashAttribute("error", map);

            return "redirect:http://auth.gulimall.com/regist.html";
        }
    }

    /**
     * 用户登录
     *
     * @param userVO   用户
     * @param redirect 重定向属性
     * @return {@link String }
     * @author DuGuanghan
     * @since 2024-08-23 10:34:56
     */
    @PostMapping("/login")
    public String login(UserVO userVO, RedirectAttributes redirect, HttpSession session) {
        // 校验用户真实性
        R r = memberFeignService.login(userVO);
        if (r.getCode() == 0) {
            MemberTo memberTo = r.getData(new TypeReference<MemberTo>() {
            });

            // 1. 解决作用域问题，默认令牌只作用于当前路由，无法作用于子域
            // 2. 使用JSON序列化的方式存储Session
            session.setAttribute("loginUser", memberTo);
            return "redirect:http://gulimall.com";
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("msg", (String) r.get("msg"));
            redirect.addFlashAttribute("error", map);

            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    public String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            // 生成0-9之间的随机数
            int digit = random.nextInt(10);
            code.append(digit);
        }
        return code.toString();
    }

}
